// 获取token
const token = new URLSearchParams(window.location.search).get('token');

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    // 加载默认页面（仪表板）
    loadPage('dashboard');
    
    // 添加导航事件监听
    document.querySelectorAll('.nav-item').forEach(item => {
        item.addEventListener('click', (e) => {
            e.preventDefault();
            document.querySelectorAll('.nav-item').forEach(i => i.classList.remove('active'));
            item.classList.add('active');
            loadPage(item.dataset.page);
        });
    });

    initImageModal();

    refreshStats();
    
    // 初始化自动刷新
    const autoRefreshCheckbox = document.getElementById('autoRefresh');
    if (autoRefreshCheckbox && autoRefreshCheckbox.checked) {
        toggleAutoRefresh(autoRefreshCheckbox);
    }

    startUserInfoUpdate();
});

// 加载页面内容
async function loadPage(pageName) {
    try {
        const response = await fetch(`/pages/${pageName}`);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const html = await response.text();
        const mainContent = document.querySelector('.main-content');
        mainContent.innerHTML = html;
        mainContent.dataset.page = pageName;
        
        // 初始化页面特定的功能
        switch(pageName) {
            case 'dashboard':
                initDashboard();
                // 立即更新用户信息
                updateUserInfo();
                break;
            case 'detect':
                initUploadArea('detectUpload', 'detectFile', 'detectPreview');
                break;
            case 'landmarks':
                initUploadArea('landmarkUpload', 'landmarkFile', 'landmarkPreview');
                break;
            case 'compare':
                initUploadArea('compareUpload1', 'compareFile1', 'comparePreview1');
                initUploadArea('compareUpload2', 'compareFile2', 'comparePreview2');
                break;
            case 'encoding':
                initUploadArea('encodingUpload', 'encodingFile', 'encodingPreview');
                break;
        }
    } catch (error) {
        showError('页面加载失败: ' + error.message);
    }
}

// 添加图片放大功能
function initImageModal() {
    // 如果已存在则移除旧的modal
    const existingModal = document.querySelector('.modal-overlay');
    if (existingModal) {
        existingModal.remove();
    }

    // 创建modal元素
    const modal = document.createElement('div');
    modal.className = 'modal-overlay';
    modal.innerHTML = `
        <span class="modal-close">&times;</span>
        <div class="modal-content">
            <div class="modal-image-container">
                <img src="" alt="放大图片">
            </div>
        </div>
        <div class="zoom-controls">
            <button class="zoom-in">放大</button>
            <button class="zoom-out">缩小</button>
            <button class="zoom-reset">重置</button>
        </div>
    `;

    // 添加到body
    document.body.appendChild(modal);

    const modalImg = modal.querySelector('.modal-content img');
    let currentScale = 1;
    const scaleStep = 0.2;
    let isDragging = false;
    let startX, startY, translateX = 0, translateY = 0;

    // 图片拖动相关事件
    modalImg.addEventListener('mousedown', startDragging);
    document.addEventListener('mousemove', drag);
    document.addEventListener('mouseup', stopDragging);
    
    // 触摸设备支持
    modalImg.addEventListener('touchstart', (e) => {
        e.preventDefault();
        const touch = e.touches[0];
        startDragging({
            clientX: touch.clientX,
            clientY: touch.clientY
        });
    });
    
    document.addEventListener('touchmove', (e) => {
        e.preventDefault();
        const touch = e.touches[0];
        drag({
            clientX: touch.clientX,
            clientY: touch.clientY,
            preventDefault: () => {}
        });
    });
    
    document.addEventListener('touchend', stopDragging);

    function startDragging(e) {
        if (e.button === 0) {  // 只响应左键点击
            isDragging = true;
            modalImg.classList.add('dragging');
            startX = e.clientX - translateX;
            startY = e.clientY - translateY;
            modalImg.style.transition = 'none';  // 拖动时禁用过渡效果
        }
    }

    function drag(e) {
        if (!isDragging) return;
        e.preventDefault();
        translateX = e.clientX - startX;
        translateY = e.clientY - startY;
        updateImageTransform();
    }

    function stopDragging() {
        if (isDragging) {
            isDragging = false;
            modalImg.classList.remove('dragging');
            modalImg.style.transition = 'transform 0.3s ease';  // 恢复过渡效果
        }
    }

    // 更新图片变换
    function updateImageTransform() {
        modalImg.style.transform = `scale(${currentScale}) translate(${translateX/currentScale}px, ${translateY/currentScale}px)`;
    }

    // 放大按钮事件
    modal.querySelector('.zoom-in').onclick = (e) => {
        e.stopPropagation();
        currentScale += scaleStep;
        updateImageTransform();
    };

    // 缩小按钮事件
    modal.querySelector('.zoom-out').onclick = (e) => {
        e.stopPropagation();
        currentScale = Math.max(0.2, currentScale - scaleStep);
        updateImageTransform();
    };

    // 重置按钮事件
    modal.querySelector('.zoom-reset').onclick = (e) => {
        e.stopPropagation();
        currentScale = 1;
        translateX = 0;
        translateY = 0;
        updateImageTransform();
    };

    // 关闭按钮事件
    const closeBtn = modal.querySelector('.modal-close');
    closeBtn.onclick = (e) => {
        e.stopPropagation();
        modal.style.display = 'none';
        resetImage();
    };

    // 点击背景关闭
    modal.onclick = (e) => {
        if (e.target === modal) {
            modal.style.display = 'none';
            resetImage();
        }
    };

    // ESC键关闭
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && modal.style.display === 'block') {
            modal.style.display = 'none';
            resetImage();
        }
    });

    // 重置图片状态
    function resetImage() {
        currentScale = 1;
        translateX = 0;
        translateY = 0;
        updateImageTransform();
    }

    // 添加鼠标滚轮缩放
    modalImg.addEventListener('wheel', (e) => {
        e.preventDefault();
        const rect = modalImg.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;

        if (e.deltaY < 0) {
            // 向上滚动，放大
            currentScale += scaleStep;
        } else {
            // 向下滚动，缩小
            currentScale = Math.max(0.2, currentScale - scaleStep);
        }
        updateImageTransform();
    });

    return modal;
}

// 使图片可点击放大
function makeImageClickable(img) {
    if (!img) return;
    img.classList.add('clickable-image');
    img.onclick = (e) => {
        e.stopPropagation();  // 阻止事件冒泡
        const modal = document.querySelector('.modal-overlay') || initImageModal();
        const modalImg = modal.querySelector('img');
        modalImg.src = img.src;
        modal.style.display = 'block';
    };
}

// 修改初始化上传区域函数
function initUploadArea(uploadId, fileId, previewId) {
    const uploadArea = document.getElementById(uploadId);
    const fileInput = document.getElementById(fileId);
    const preview = document.getElementById(previewId);

    if (!uploadArea || !fileInput || !preview) return;

    // 点击上传区域的处理
    uploadArea.onclick = (e) => {
        // 如果点击的是预览图片，不触发文件选择
        if (e.target === preview) {
            return;
        }
        fileInput.click();
    };

    // 文件选择变化的处理
    fileInput.onchange = (e) => {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                preview.src = e.target.result;
                preview.style.display = 'block';
                makeImageClickable(preview);
            };
            reader.readAsDataURL(file);
        }
    };

    // 拖放处理
    uploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        uploadArea.style.borderColor = '#2196F3';
    });

    uploadArea.addEventListener('dragleave', (e) => {
        e.preventDefault();
        uploadArea.style.borderColor = '#ccc';
    });

    uploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadArea.style.borderColor = '#ccc';
        const file = e.dataTransfer.files[0];
        if (file) {
            fileInput.files = e.dataTransfer.files;
            const reader = new FileReader();
            reader.onload = (e) => {
                preview.src = e.target.result;
                preview.style.display = 'block';
                makeImageClickable(preview);
            };
            reader.readAsDataURL(file);
        }
    });
}

// 显示错误信息
function showError(message) {
    const content = document.querySelector('.main-content');
    content.innerHTML = `
        <div class="error-message">
            <i class="error-icon">⚠</i>
            <div class="error-text">${message}</div>
        </div>
    `;
}

// 退出登录
async function logout() {
    try {
        await fetch('/logout?token=' + token);
        localStorage.removeItem('token');
        window.location.href = '/';
    } catch (error) {
        showError('退出失败: ' + error.message);
    }
}

// 人脸检测
async function detectFace(endpoint) {
    const file = document.getElementById('detectFile').files[0];
    if (!file) {
        showAlert('请先选择图片');
        return;
    }

    const loading = document.getElementById('detectLoading');
    const result = document.getElementById('detectResult');
    loading.style.display = 'block';
    result.innerHTML = '';

    const formData = new FormData();
    formData.append('imgFile', file);

    try {
        const response = await fetch(`/faceapi/v1/${endpoint}`, {
            method: 'POST',
            headers: {
                'Authorization': token
            },
            body: formData
        });
        
        // 检查响应状态
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();

        if (data.success) {
            switch (endpoint) {
                case 'detectBox':
                    showBoxResults(data.data);
                    break;
                case 'detectFace':
                    showFaceResults(data.data);
                    break;
                case 'detectDrawBox':
                    showDrawResults(data.data);
                    break;
            }
        } else {
            showAlert(data.msg || '处理失败');
        }
    } catch (error) {
        if (error.name === 'SyntaxError') {
            showAlert('服务器返回数据格式错误，请稍后重试');
        } else {
            showAlert(error.message || '请求失败，请稍后重试');
        }
    } finally {
        loading.style.display = 'none';
    }
}

// 显示人脸框坐标结果
function showBoxResults(data) {
    const result = document.getElementById('detectResult');
    result.innerHTML = `
        <div class="result-header">
            <h3>检测到 ${data.count} 个人脸</h3>
        </div>
        <div class="result-content">
            <div class="coordinates-list">
                ${data.boxes.map((box, index) => `
                    <div class="coordinate-item">
                        <div class="coordinate-label">人脸 ${index + 1}:</div>
                        <div class="coordinate-values">
                            <div>上: ${box[0]}</div>
                            <div>右: ${box[1]}</div>
                            <div>下: ${box[2]}</div>
                            <div>左: ${box[3]}</div>
                        </div>
                    </div>
                `).join('')}
            </div>
        </div>
    `;
}

// 修改显示人脸结果的函数
function showFaceResults(data) {
    const result = document.getElementById('detectResult');
    result.innerHTML = `
        <div class="result-header">
            <h3>检测到 ${data.count} 个人脸</h3>
        </div>
        <div class="result-content face-grid">
            ${data.faces.map((face, index) => `
                <div class="face-item">
                    <img src="data:image/jpeg;base64,${face}" alt="Face ${index + 1}" class="clickable-image">
                    <div class="face-label">人脸 ${index + 1}</div>
                </div>
            `).join('')}
        </div>
    `;
    // 为所有结果图片添加点击事件
    result.querySelectorAll('img').forEach(makeImageClickable);
}

// 修改显示绘制结果的函数
function showDrawResults(data) {
    const result = document.getElementById('detectResult');
    result.innerHTML = `
        <div class="result-header">
            <h3>检测到 ${data.count} 个人脸</h3>
        </div>
        <div class="result-content">
            <img src="data:image/jpeg;base64,${data.image}" alt="Detected faces" class="result-image clickable-image">
        </div>
    `;
    makeImageClickable(result.querySelector('img'));
}

// 特征点检测
async function detectLandmarks(endpoint) {
    const file = document.getElementById('landmarkFile').files[0];
    if (!file) {
        showAlert('请先选择图片');
        return;
    }

    const loading = document.getElementById('landmarkLoading');
    const result = document.getElementById('landmarkResult');
    loading.style.display = 'block';
    result.innerHTML = '';

    const formData = new FormData();
    formData.append('imgFile', file);

    try {
        const response = await fetch(`/faceapi/v1/${endpoint}`, {
            method: 'POST',
            headers: {
                'Authorization': token
            },
            body: formData
        });
        const data = await response.json();

        if (data.success) {
            if (endpoint === 'landmarksPoint') {
                // 显示特征点坐标
                result.innerHTML = `
                    <h3>检测到 ${data.data.face_landmarks_list.length} 个人脸的特征点</h3>
                    <pre>${JSON.stringify(data.data.face_landmarks_list, null, 2)}</pre>
                `;
            } else {
                result.innerHTML = `
                    <h3>处理结果</h3>
                    <img src="data:image/jpeg;base64,${data.data.image}" class="preview-image clickable-image">
                `;
                makeImageClickable(result.querySelector('img'));
            }
        } else {
            result.innerHTML = `<div class="error-message">${data.msg}</div>`;
        }
    } catch (error) {
        result.innerHTML = `<div class="error-message">请求失败: ${error.message}</div>`;
    } finally {
        loading.style.display = 'none';
    }
}

// 人脸对比
async function compareFaces() {
    const file1 = document.getElementById('compareFile1').files[0];
    const file2 = document.getElementById('compareFile2').files[0];
    if (!file1 || !file2) {
        showAlert('请选择两张图片进行对比');
        return;
    }

    const loading = document.getElementById('compareLoading');
    const result = document.getElementById('compareResult');
    loading.style.display = 'block';
    result.innerHTML = '';

    const formData = new FormData();
    formData.append('imgFile1', file1);
    formData.append('imgFile2', file2);

    try {
        const response = await fetch('/faceapi/v1/recognizeCompareImage', {
            method: 'POST',
            headers: {
                'Authorization': token
            },
            body: formData
        });
        const data = await response.json();

        if (data.success) {
            const isMatch = data.data.compare_result[0];
            result.innerHTML = `<div style="text-align: center; font-size: 1.2em; color: ${isMatch ? 'green' : 'red'}">
                ${isMatch ? '是同一个人' : '不是同一个人'}
            </div>`;
        } else {
            result.textContent = `错误: ${data.msg}`;
        }
    } catch (error) {
        result.textContent = `请求失败: ${error.message}`;
    } finally {
        loading.style.display = 'none';
    }
}

// 添加刷新统计数据的函数
async function refreshStats() {
    try {
        const response = await fetch('/api/stats', {
            headers: {
                'Authorization': token
            }
        });
        const data = await response.json();
        
        if (data.success) {
            // 更新统计数据
            document.getElementById('detectCount').textContent = data.data.system_stats.detect_count || 'NaN';
            document.getElementById('landmarksCount').textContent = data.data.system_stats.landmarks_count || 'NaN';
            document.getElementById('compareCount').textContent = data.data.system_stats.compare_count || 'NaN';
            document.getElementById('encodingCount').textContent = data.data.system_stats.encoding_count || 'NaN';
            
            // 更新性能指标
            document.getElementById('avgResponseTime').textContent = 
                `${data.data.system_stats.avg_response_time || 'undefined'}ms`;
            document.getElementById('successRate').textContent = 
                `${data.data.system_stats.success_rate || 'undefined'}%`;
            
            // 更新历史记录
            updateHistoryList(data.data.recent_records || []);
        }
    } catch (error) {
        console.error('刷新统计数据失败:', error);
    }
}

// 更新历史记录列表
function updateHistoryList(records) {
    const historyList = document.getElementById('usageHistory');
    if (!historyList) return;  // 如果元素不存在则返回
    
    const filter = document.getElementById('historyFilter')?.value || 'all';
    
    const historyHtml = records
        .filter(record => filter === 'all' || 
                         (filter === 'success' && record.status === '成功') ||
                         (filter === 'error' && record.status !== '成功'))
        .map(record => `
            <div class="history-item">
                <div class="history-time">${record.time}</div>
                <div class="history-content">
                    <div class="history-function">${record.function}</div>
                    <div class="history-details">
                        <span>处理时间: ${record.processTime}ms</span>
                        <span class="status-badge ${record.status === '成功' ? 'success' : 'error'}">
                            ${record.status}
                        </span>
                    </div>
                </div>
            </div>
        `).join('');
    
    historyList.innerHTML = historyHtml || '<div class="no-records">暂无操作记录</div>';
}

// 自动刷新控制
let refreshInterval;

function toggleAutoRefresh(checkbox) {
    if (checkbox.checked) {
        refreshInterval = setInterval(refreshStats, 5000); // 每5秒刷新一次
    } else {
        clearInterval(refreshInterval);
    }
}

// 过滤历史记录
function filterHistory(value) {
    refreshStats();
}

// 添加获取人脸编码的函数
async function getEncoding() {
    const file = document.getElementById('encodingFile').files[0];
    if (!file) {
        showAlert('请先选择图片');
        return;
    }

    const loading = document.getElementById('encodingLoading');
    const result = document.getElementById('encodingResult');
    loading.style.display = 'block';
    result.innerHTML = '';

    const formData = new FormData();
    formData.append('imgFile', file);

    try {
        const response = await fetch('/faceapi/v1/recognizeEncoding', {
            method: 'POST',
            headers: {
                'Authorization': token
            },
            body: formData
        });
        const data = await response.json();

        if (data.success) {
            result.textContent = JSON.stringify(data.data.encoding, null, 2);
        } else {
            result.textContent = `错误: ${data.msg}`;
        }
    } catch (error) {
        result.textContent = `请求失败: ${error.message}`;
    } finally {
        loading.style.display = 'none';
    }
}

// 添加使用记录加载函数
async function loadUsageHistory() {
    try {
        const response = await fetch('/api/usage-history', {
            headers: {
                'Authorization': token
            }
        });
        const data = await response.json();
        
        if (data.success) {
            const historyContainer = document.getElementById('usageHistory');
            if (historyContainer) {
                historyContainer.innerHTML = `
                    <div class="history-list">
                        ${data.data.history.map(record => `
                            <div class="history-item">
                                <div class="history-time">${record.time}</div>
                                <div class="history-content">
                                    <div class="history-function">${record.function}</div>
                                    <div class="history-details">${record.details}</div>
                                </div>
                            </div>
                        `).join('')}
                    </div>
                `;
            }
        }
    } catch (error) {
        console.error('加载使用记录失败:', error);
    }
}

// 修改提示函数为自定义提示框
function showAlert(message) {
    const alertOverlay = document.createElement('div');
    alertOverlay.className = 'alert-overlay';
    alertOverlay.innerHTML = `
        <div class="alert-box">
            <div class="alert-content">${message}</div>
            <div class="alert-buttons">
                <button class="alert-button">确定</button>
            </div>
        </div>
    `;

    document.body.appendChild(alertOverlay);

    const closeAlert = () => {
        alertOverlay.remove();
    };

    // 点击确定按钮关闭
    alertOverlay.querySelector('.alert-button').onclick = closeAlert;

    // ESC键关闭
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') {
            closeAlert();
        }
    });

    // 点击背景关闭
    alertOverlay.onclick = (e) => {
        if (e.target === alertOverlay) {
            closeAlert();
        }
    };
}

// 修改更新用户信息函数，添加错误处理和重试机制
async function updateUserInfo() {
    try {
        const response = await fetch('/api/user-info', {
            headers: {
                'Authorization': token
            }
        });
        
        if (!response.ok) {
            throw new Error('获取用户信息失败');
        }
        
        const data = await response.json();
        
        if (data.success) {
            // 更新欢迎语和账户信息
            const welcomeUsername = document.getElementById('welcomeUsername');
            const accountUsername = document.getElementById('accountUsername');
            const lastLoginTime = document.getElementById('lastLoginTime');
            const currentLoginTime = document.getElementById('currentLoginTime');
            const totalOperations = document.getElementById('totalOperations');
            const successOperations = document.getElementById('successOperations');
            const userSuccessRate = document.getElementById('userSuccessRate');
            
            // 检查元素是否存在再更新
            if (welcomeUsername) welcomeUsername.textContent = data.data.username;
            if (accountUsername) accountUsername.textContent = data.data.username;
            if (lastLoginTime) lastLoginTime.textContent = data.data.lastLogin;
            if (currentLoginTime) currentLoginTime.textContent = data.data.currentLoginTime;
            if (totalOperations) totalOperations.textContent = data.data.totalOperations;
            if (successOperations) successOperations.textContent = data.data.successOperations;
            if (userSuccessRate) userSuccessRate.textContent = data.data.successRate;
        }
    } catch (error) {
        console.error('更新用户信息失败:', error);
        // 如果是在仪表板页面，3秒后重试
        if (document.querySelector('.main-content').dataset.page === 'dashboard') {
            setTimeout(updateUserInfo, 3000);
        }
    }
}

// 修改定期更新用户信息的函数
function startUserInfoUpdate() {
    // 清除可能存在的旧定时器
    if (window.userInfoUpdateInterval) {
        clearInterval(window.userInfoUpdateInterval);
    }
    
    // 立即更新一次
    updateUserInfo();
    
    // 设置新的定时器
    window.userInfoUpdateInterval = setInterval(updateUserInfo, 15000);
}

// 添加图表初始化函数
function initCharts() {
    // 初始化响应时间图表
    const responseTimeCtx = document.getElementById('responseTimeChart');
    if (responseTimeCtx) {
        window.responseTimeChart = new Chart(responseTimeCtx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: '响应时间 (ms)',
                    data: [],
                    borderColor: '#2196F3',
                    tension: 0.4,
                    fill: false
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }

    // 初始化成功率图表
    const successRateCtx = document.getElementById('successRateChart');
    if (successRateCtx) {
        window.successRateChart = new Chart(successRateCtx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: '成功率 (%)',
                    data: [],
                    borderColor: '#4CAF50',
                    tension: 0.4,
                    fill: false
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100
                    }
                }
            }
        });
    }
}

// 添加性能指标更新函数
function updatePerformanceMetrics(data) {
    // 更新数值显示
    document.getElementById('avgResponseTime').textContent = `${data.avgResponseTime}ms`;
    document.getElementById('successRate').textContent = `${data.successRate}%`;

    // 获取当前时间作为标签
    const now = new Date().toLocaleTimeString();

    // 更新响应时间图表
    if (window.responseTimeChart) {
        const chart = window.responseTimeChart;
        chart.data.labels.push(now);
        chart.data.datasets[0].data.push(data.avgResponseTime);

        // 保持最近10个数据点
        if (chart.data.labels.length > 10) {
            chart.data.labels.shift();
            chart.data.datasets[0].data.shift();
        }
        chart.update();
    }

    // 更新成功率图表
    if (window.successRateChart) {
        const chart = window.successRateChart;
        chart.data.labels.push(now);
        chart.data.datasets[0].data.push(data.successRate);

        // 保持最近10个数据点
        if (chart.data.labels.length > 10) {
            chart.data.labels.shift();
            chart.data.datasets[0].data.shift();
        }
        chart.update();
    }
}

// 添加自动刷新功能
function initDashboard() {
    // 初始化图表
    initCharts();
    
    // 初始加载数据
    refreshStats();
    
    // 设置自动刷新
    const autoRefreshCheckbox = document.getElementById('autoRefresh');
    if (autoRefreshCheckbox && autoRefreshCheckbox.checked) {
        toggleAutoRefresh(autoRefreshCheckbox);
    }
}

// 更新顶部栏用户信息
function updateCurrentUser(username) {
    const currentUser = document.getElementById('currentUser');
    if (currentUser) {
        currentUser.textContent = `当前用户：${username}`;
    }
}

// 显示退出确认弹窗
function showLogoutConfirm() {
    // 创建弹窗元素
    const confirmDialog = document.createElement('div');
    confirmDialog.className = 'logout-confirm';
    confirmDialog.innerHTML = `
        <div class="logout-confirm-box">
            <h3>确认退出登录？</h3>
            <div class="logout-confirm-buttons">
                <button class="cancel-logout" onclick="closeLogoutConfirm()">取消</button>
                <button class="confirm-logout" onclick="logout()">确认退出</button>
            </div>
        </div>
    `;
    
    document.body.appendChild(confirmDialog);
    
    // 显示动画
    setTimeout(() => {
        confirmDialog.classList.add('show');
    }, 10);
}

// 关闭退出确认弹窗
function closeLogoutConfirm() {
    const confirmDialog = document.querySelector('.logout-confirm');
    if (confirmDialog) {
        confirmDialog.classList.remove('show');
        setTimeout(() => {
            confirmDialog.remove();
        }, 300);
    }
}

// 切换密码显示/隐藏
function togglePassword() {
    const passwordSpan = document.getElementById('accountPassword');
    const toggleIcon = document.querySelector('.password-toggle');
    
    if (passwordSpan.textContent === '********') {
        // 获取实际密码
        fetch('/api/user-password', {
            headers: {
                'Authorization': token
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                passwordSpan.textContent = data.data.password;
                toggleIcon.classList.remove('fa-eye');
                toggleIcon.classList.add('fa-eye-slash');
            }
        });
    } else {
        passwordSpan.textContent = '********';
        toggleIcon.classList.remove('fa-eye-slash');
        toggleIcon.classList.add('fa-eye');
    }
}

// 显示修改密码模态框
function showChangePasswordModal() {
    document.getElementById('changePasswordModal').style.display = 'block';
}

// 关闭修改密码模态框
function closeChangePasswordModal() {
    document.getElementById('changePasswordModal').style.display = 'none';
    document.getElementById('changePasswordForm').reset();
}

// 处理修改密码
async function handleChangePassword(event) {
    event.preventDefault();
    
    const oldPassword = document.getElementById('oldPassword').value;
    const newPassword = document.getElementById('newPassword').value;
    const confirmPassword = document.getElementById('confirmPassword').value;
    
    if (newPassword !== confirmPassword) {
        showAlert('新密码与确认密码不一致');
        return false;
    }
    
    try {
        const response = await fetch('/api/change-password', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': token
            },
            body: JSON.stringify({
                oldPassword,
                newPassword
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            showAlert('密码修改成功');
            closeChangePasswordModal();
            // 更新显示的密码
            document.getElementById('accountPassword').textContent = '********';
        } else {
            showAlert(data.msg || '密码修改失败');
        }
    } catch (error) {
        showAlert('请求失败，请稍后重试');
    }
    
    return false;
}

// 添加滚动控制函数
function scrollToTop() {
    const mainContent = document.querySelector('.main-content');
    mainContent.scrollTo({
        top: 0,
        behavior: 'smooth'
    });
}

function scrollToBottom() {
    const mainContent = document.querySelector('.main-content');
    mainContent.scrollTo({
        top: mainContent.scrollHeight,
        behavior: 'smooth'
    });
}

// 控制按钮显示/隐藏
document.addEventListener('DOMContentLoaded', function() {
    const mainContent = document.querySelector('.main-content');
    const scrollButtons = document.querySelector('.scroll-buttons');
    
    // 初始隐藏按钮
    scrollButtons.style.display = 'none';
    
    mainContent.addEventListener('scroll', function() {
        // 如果内容高度大于容器高度，显示按钮
        if (mainContent.scrollHeight > mainContent.clientHeight) {
            scrollButtons.style.display = 'flex';
            
            // 根据滚动位置添加动画类
            if (mainContent.scrollTop > 100) {
                scrollButtons.querySelector('.scroll-top').classList.add('fade-in');
                scrollButtons.querySelector('.scroll-top').classList.remove('fade-out');
            } else {
                scrollButtons.querySelector('.scroll-top').classList.add('fade-out');
                scrollButtons.querySelector('.scroll-top').classList.remove('fade-in');
            }
            
            if (mainContent.scrollHeight - mainContent.scrollTop - mainContent.clientHeight > 100) {
                scrollButtons.querySelector('.scroll-bottom').classList.add('fade-in');
                scrollButtons.querySelector('.scroll-bottom').classList.remove('fade-out');
            } else {
                scrollButtons.querySelector('.scroll-bottom').classList.add('fade-out');
                scrollButtons.querySelector('.scroll-bottom').classList.remove('fade-in');
            }
        } else {
            scrollButtons.style.display = 'none';
        }
    });
});

// 获取可用的测试图片列表
async function getTestImages(type) {
    try {
        const response = await fetch(`/api/test-images?type=${type}`);
        const data = await response.json();
        return data.images;
    } catch (error) {
        console.error('获取测试图片列表失败:', error);
        return [];
    }
}

// 显示测试图片选择下拉菜单
async function showTestImageSelect(type) {
    const dropdown = document.getElementById(`${type}TestSelect`);
    if (!dropdown) return;

    // 如果已经显示则隐藏
    if (dropdown.classList.contains('show')) {
        dropdown.classList.remove('show');
        return;
    }

    // 获取测试图片列表
    const images = await getTestImages(type);
    
    // 根据类型生成不同的下拉菜单内容
    if (type === 'compare') {
        // 对比功能的下拉菜单
        dropdown.innerHTML = images.map((img, index) => `
            <div class="test-select-item" onclick="loadCompareTestImages('${img}')">
                <i class="fas fa-images"></i>
                对比示例${index + 1}
            </div>
        `).join('');
    } else {
        // 其他功能的下拉菜单
        dropdown.innerHTML = images.map(img => `
            <div class="test-select-item" onclick="loadTestImage('${type}', '${img}')">
                <i class="fas fa-image"></i>
                ${img.replace(`${type}_`, '示例').replace('.jpg', '')}
            </div>
        `).join('');
    }

    // 显示下拉菜单
    dropdown.classList.add('show');

    // 点击其他地方关闭下拉菜单
    document.addEventListener('click', function closeDropdown(e) {
        if (!dropdown.contains(e.target) && 
            !e.target.closest('.test-button')) {
            dropdown.classList.remove('show');
            document.removeEventListener('click', closeDropdown);
        }
    });
}

// 修改加载测试图片函数
async function loadTestImage(type, imageName) {
    // 根据不同类型使用不同的ID
    const fileId = type === 'landmarks' ? 'landmarkFile' : 
                   type === 'detect' ? 'detectFile' :
                   type === 'encoding' ? 'encodingFile' : null;
                   
    const previewId = type === 'landmarks' ? 'landmarkPreview' :
                      type === 'detect' ? 'detectPreview' :
                      type === 'encoding' ? 'encodingPreview' : null;
    
    if (!fileId || !previewId) {
        console.error('Invalid type:', type);
        return;
    }
    
    const fileInput = document.getElementById(fileId);
    const preview = document.getElementById(previewId);
    
    if (!fileInput || !preview) {
        console.error('Elements not found:', fileId, previewId);
        return;
    }
    
    try {
        // 获取示例图片
        const response = await fetch(`/data/examples/${imageName}`);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const blob = await response.blob();
        
        // 创建File对象
        const file = new File([blob], imageName, { type: 'image/jpeg' });
        
        try {
            // 创建FileList对象
            const dataTransfer = new DataTransfer();
            dataTransfer.items.add(file);
            fileInput.files = dataTransfer.files;
            
            // 显示预览
            const reader = new FileReader();
            reader.onload = (e) => {
                preview.src = e.target.result;
                preview.style.display = 'block';
                makeImageClickable(preview);
            };
            reader.readAsDataURL(file);
            
            // 关闭下拉菜单
            const dropdown = document.getElementById(`${type}TestSelect`);
            if (dropdown) {
                dropdown.classList.remove('show');
            }
        } catch (e) {
            console.error('Error setting files:', e);
            showAlert('您的浏览器可能不支持此功能，请直接上传图片');
        }
        
    } catch (error) {
        console.error('Error loading test image:', error);
        showAlert('加载测试图片失败: ' + error.message);
    }
}

// 修改对比测试图片加载函数
async function loadCompareTestImages(testSet) {
    const fileInput1 = document.getElementById('compareFile1');
    const fileInput2 = document.getElementById('compareFile2');
    const preview1 = document.getElementById('comparePreview1');
    const preview2 = document.getElementById('comparePreview2');
    
    if (!fileInput1 || !fileInput2 || !preview1 || !preview2) {
        console.error('Compare elements not found');
        return;
    }
    
    try {
        // 获取示例图片对
        const [img1, img2] = testSet.split(',');
        const response1 = await fetch(`/data/examples/${img1}`);
        const response2 = await fetch(`/data/examples/${img2}`);
        
        if (!response1.ok || !response2.ok) {
            throw new Error('Failed to fetch test images');
        }
        
        const blob1 = await response1.blob();
        const blob2 = await response2.blob();
        
        // 创建File对象
        const file1 = new File([blob1], img1, { type: 'image/jpeg' });
        const file2 = new File([blob2], img2, { type: 'image/jpeg' });
        
        try {
            // 设置文件和预览
            const dt1 = new DataTransfer();
            dt1.items.add(file1);
            fileInput1.files = dt1.files;
            
            const dt2 = new DataTransfer();
            dt2.items.add(file2);
            fileInput2.files = dt2.files;
            
            // 显示预览
            const reader1 = new FileReader();
            reader1.onload = (e) => {
                preview1.src = e.target.result;
                preview1.style.display = 'block';
                makeImageClickable(preview1);
            };
            reader1.readAsDataURL(file1);
            
            const reader2 = new FileReader();
            reader2.onload = (e) => {
                preview2.src = e.target.result;
                preview2.style.display = 'block';
                makeImageClickable(preview2);
            };
            reader2.readAsDataURL(file2);
            
            // 关闭下拉菜单
            const dropdown = document.getElementById('compareTestSelect');
            if (dropdown) {
                dropdown.classList.remove('show');
            }
        } catch (e) {
            console.error('Error setting files:', e);
            showAlert('您的浏览器可能不支持此功能，请直接上传图片');
        }
        
    } catch (error) {
        console.error('Error loading test images:', error);
        showAlert('加载测试图片失败: ' + error.message);
    }
} 